package com.spring.handler;

import com.spring.http.HttpServlet;
import com.spring.server.KingContext;
import com.spring.server.KingHost;
import com.spring.server.KingService;
import com.spring.server.KingWrapper;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.List;

/**
 * @author Spring King
 * @date 2021/7/11
 */
public class ResourceLoader {

    private static final KingService service = new KingService();

    /**
     * 加载解析项目中的web.xml
     */
    public static KingContext loadContextServlet(String path) {
        KingContext context = new KingContext();
        String webPath = path + File.separator + "web.xml";
        try {
            InputStream inputStream = new FileInputStream(webPath);
            Document document = new SAXReader().read(inputStream);
            Element rootElement = document.getRootElement();

            List<Element> nodes = rootElement.selectNodes("//servlet");
            for (Element node : nodes) {
                Element servletNameNode = (Element) node.selectSingleNode("servlet-name");
                String servletName = servletNameNode.getStringValue();
                // servletClass
                Element servletClassNode = (Element) node.selectSingleNode("servlet-class");
                String servletClass = servletClassNode.getStringValue();
                // urlPattern
                Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
                String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();
                // 自定义ClassLoader load webapps classes
                WebClassLoader webClassLoader = new WebClassLoader();
                Class<?> webClassLoaderClass = webClassLoader.findClass(path, servletClass);
                KingWrapper wrapper = new KingWrapper(urlPattern, (HttpServlet) webClassLoaderClass.getConstructor().newInstance());
                context.addWrapper(wrapper);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return context;
    }

    /**
     * todo activate WebClassLoader
     * 加载解析 server.xml，并初始化 webapps下各个项目的 Servlet
     */
    public static KingService loadServlet() {
        InputStream resourceAsStream = ResourceLoader.class.getClassLoader().getResourceAsStream("server.xml");
        SAXReader saxReader = new SAXReader();
        try {
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();
            // 解析 server 标签
            Element serverElement = (Element) rootElement.selectSingleNode("//server");
            // 解析 service 标签
            Element serviceNode = (Element) serverElement.selectSingleNode("service");
            // 解析 connector
            Element connectorNode = (Element) serviceNode.selectSingleNode("connector");
            String port = connectorNode.attributeValue("port");
            service.setPort(Integer.parseInt(port));
            // engine
            Element engineNode = (Element) serviceNode.selectSingleNode("engine");
            List<Element> hostNodes = engineNode.selectNodes("host");
            for (Element hostNode : hostNodes) {
                String name = hostNode.attributeValue("name");
                String appBase = hostNode.attributeValue("appBase");
                // host
                KingHost host = new KingHost(name);

                File file = new File(appBase);
                if (!file.exists() || file.list() == null) {
                    break;
                }
                for (String path : file.list()) {
                    // context
                    host.addContest(loadContextServlet(appBase + File.separator + path));
                }
                service.addHost(host);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return service;
    }
}
